package com.hyperfix.common.utils;

import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author JiangChunYu
 * 2024/4/17
 */
@SuppressWarnings("unused")
@Component
public class MutexUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 互斥锁最大存活时间
     */
    private static final long MUTEX_LOCK_TTL = 10L;

    public boolean tryLock(String key) {
        Boolean absent = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", MUTEX_LOCK_TTL, TimeUnit.SECONDS);
        return Boolean.TRUE.equals(absent);
    }

    public void unlock(String key) {
        stringRedisTemplate.delete(key);
    }
}
